<template>
  <div class="cyber-menu-container" ref="container">
    <canvas ref="bgCanvas" class="background-canvas"></canvas>
    <div class="menu-content" :style="{ opacity: contentOpacity }" ref="menuContent">
      <div class="menu-header">
        <h1 class="cyber-title">CYBER BREW</h1>
        <div class="cyber-subtitle">DIGITAL CRAFT BEER SELECTION</div>
      </div>
      
      <div class="beer-grid">
        <div v-for="(beer, index) in beers" 
             :key="index" 
             class="beer-card"
             :class="{ 'active': activeIndex === index }"
             @mouseenter="activeIndex = index"
             @mouseleave="activeIndex = null">
          <div class="beer-number">{{ String(index + 1).padStart(2, '0') }}</div>
          <div class="beer-info">
            <h3 class="beer-name">{{ beer.name }}</h3>
            <div class="beer-style">{{ beer.style }}</div>
            <div class="beer-stats">
              <span class="abv">ABV {{ beer.abv }}%</span>
              <span class="ibu">IBU {{ beer.ibu }}</span>
            </div>
            <div class="beer-description">{{ beer.description }}</div>
          </div>
          <div class="beer-prices">
            <div class="price-item">
              <svg class="beer-icon small" viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor" d="M15,14.77V3H9V14.77C7.18,15.14 6,16.7 6,18.5C6,20.43 7.57,22 9.5,22C11.43,22 13,20.43 13,18.5V18.29C13,18.29 15,18.5 15,18.5C15,16.7 13.82,15.14 12,14.77M9,6H15V8H9V6M9,10H15V12H9V10Z" />
              </svg>
              <span class="price">¥{{ beer.price - 10 }}</span>
            </div>
            <div class="price-item">
              <svg class="beer-icon large" viewBox="0 0 24 24" width="32" height="32">
                <path fill="currentColor" d="M15,14.77V3H9V14.77C7.18,15.14 6,16.7 6,18.5C6,20.43 7.57,22 9.5,22C11.43,22 13,20.43 13,18.5V18.29C13,18.29 15,18.5 15,18.5C15,16.7 13.82,15.14 12,14.77M9,6H15V8H9V6M9,10H15V12H9V10Z" />
              </svg>
              <span class="price">¥{{ beer.price }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 导出按钮 -->
    <button 
      class="export-button" 
      @click="exportImage"
      :disabled="exporting"
    >
      <svg v-if="!exporting" class="w-6 h-6" viewBox="0 0 24 24">
        <path fill="currentColor" d="M4,2H14V4H4V14H2V4C2,2.89 2.89,2 4,2M8,6H18V8H8V18H6V8C6,6.89 6.89,6 8,6M12,10H20C21.11,10 22,10.89 22,12V20C22,21.11 21.11,22 20,22H12C10.89,22 10,21.11 10,20V12C10,10.89 10.89,10 12,10M14,12V20H20V12H14Z" />
      </svg>
      <div v-else class="loading-spinner"></div>
      {{ exporting ? '导出中...' : '导出图片' }}
    </button>
    <div class="export-buttons">
      <button class="cyber-button" @click="exportAsImage">
        <i class="fas fa-image"></i> 导出图片
      </button>
      <button class="cyber-button" @click="exportForCanvas">
        <i class="fas fa-graduation-cap"></i> 导出到 Canvas
      </button>
      <button class="cyber-button" @click="goToDisplay">
        <i class="fas fa-tv"></i> 展示模式
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import html2canvas from 'html2canvas'
import JSZip from 'jszip'

const router = useRouter()

// 啤酒数据
const beers = ref([
  {
    name: "NEON HAZE",
    style: "New England IPA",
    abv: 6.8,
    ibu: 65,
    price: 58,
    description: "浊色多汁的新英格兰IPA，热带水果风味"
  },
  {
    name: "DIGITAL STOUT",
    style: "Imperial Stout",
    abv: 9.5,
    ibu: 75,
    price: 68,
    description: "浓郁的咖啡和黑巧克力风味，数字时代的醇厚"
  },
  {
    name: "MATRIX LAGER",
    style: "Japanese Rice Lager",
    abv: 4.5,
    ibu: 18,
    price: 48,
    description: "清爽干净的日式啤酒，完美平衡"
  },
  {
    name: "CYBER WHEAT",
    style: "Hefeweizen",
    abv: 5.2,
    ibu: 12,
    price: 52,
    description: "香蕉丁香风味，未来感德式小麦"
  },
  {
    name: "PIXEL PALE",
    style: "American Pale Ale",
    abv: 5.5,
    ibu: 40,
    price: 55,
    description: "清新柑橘和松树风味，8-bit复古风格"
  },
  {
    name: "BINARY BLONDE",
    style: "Belgian Blonde",
    abv: 6.5,
    ibu: 25,
    price: 58,
    description: "比利时酵母带来的水果香气，0和1的完美结合"
  },
  {
    name: "QUANTUM QUAD",
    style: "Quadrupel",
    abv: 10.5,
    ibu: 30,
    price: 78,
    description: "深邃复杂的比利时四料，量子纠缠的味觉体验"
  },
  {
    name: "HOLOGRAM HELLES",
    style: "Munich Helles",
    abv: 4.8,
    ibu: 20,
    price: 52,
    description: "清澈金黄的慕尼黑啤酒，全息投影般纯净"
  },
  {
    name: "NEURAL NEIPA",
    style: "Double NEIPA",
    abv: 8.0,
    ibu: 70,
    price: 68,
    description: "加倍的热带水果风暴，人工智能调制"
  },
  {
    name: "SYNTH SAISON",
    style: "Saison",
    abv: 6.2,
    ibu: 25,
    price: 56,
    description: "农舍酵母的独特个性，合成器般的律动"
  },
  {
    name: "LASER LAGER",
    style: "German Pilsner",
    abv: 4.8,
    ibu: 30,
    price: 48,
    description: "德式皮尔森的完美平衡，激光般的清澈"
  },
  {
    name: "VOID PORTER",
    style: "Baltic Porter",
    abv: 7.5,
    ibu: 35,
    price: 62,
    description: "黑洞般深邃的波罗的海波特，醇厚绵密"
  },
  {
    name: "GLITCH GOSE",
    style: "Gose",
    abv: 4.2,
    ibu: 8,
    price: 54,
    description: "带有海盐和香菜籽风味的德式酸啤，系统故障般独特"
  },
  {
    name: "CRYPTO KOLSCH",
    style: "Kölsch",
    abv: 4.8,
    ibu: 25,
    price: 52,
    description: "科隆特色的清爽啤酒，加密货币般的未来感"
  },
  {
    name: "PLASMA PALE",
    style: "Pacific Pale Ale",
    abv: 5.8,
    ibu: 45,
    price: 56,
    description: "充满热带水果风味的淡色啤酒，等离子般绚丽"
  },
  {
    name: "TECH TRIPEL",
    style: "Belgian Tripel",
    abv: 8.5,
    ibu: 35,
    price: 68,
    description: "复杂的比利时三料，高科技酿造工艺"
  },
  {
    name: "RAM RED",
    style: "Irish Red Ale",
    abv: 5.0,
    ibu: 25,
    price: 54,
    description: "焦糖麦芽风味的红色艾尔，内存条般闪耀"
  },
  {
    name: "STATIC STOUT",
    style: "Milk Stout",
    abv: 5.5,
    ibu: 30,
    price: 58,
    description: "乳糖带来丝滑口感，电流噪声般迷人"
  },
  {
    name: "CYBER SOUR",
    style: "Berliner Weisse",
    abv: 3.8,
    ibu: 5,
    price: 52,
    description: "清爽酸甜的柏林酸小麦，数字时代的清新"
  },
  {
    name: "MATRIX MALT",
    style: "Scotch Ale",
    abv: 7.8,
    ibu: 28,
    price: 65,
    description: "焦糖麦芽风味浓郁，矩阵般层次丰富"
  }
])

const container = ref(null)
const bgCanvas = ref(null)
const ctx = ref(null)
const contentOpacity = ref(0)
const activeIndex = ref(null)

// Canvas 动画相关变量
let animationFrame = null
let particles = []
const PARTICLE_COUNT = 100
const PARTICLE_SPEED = 0.5
const CONNECT_DISTANCE = 100

// 初始化粒子
function initParticles() {
  const { width, height } = bgCanvas.value
  particles = []
  
  for (let i = 0; i < PARTICLE_COUNT; i++) {
    particles.push({
      x: Math.random() * width,
      y: Math.random() * height,
      vx: (Math.random() - 0.5) * PARTICLE_SPEED,
      vy: (Math.random() - 0.5) * PARTICLE_SPEED,
      size: Math.random() * 2 + 1
    })
  }
}

// 更新粒子位置
function updateParticles() {
  const { width, height } = bgCanvas.value
  
  particles.forEach(p => {
    p.x += p.vx
    p.y += p.vy

    if (p.x < 0 || p.x > width) p.vx *= -1
    if (p.y < 0 || p.y > height) p.vy *= -1
  })
}

// 绘制粒子和连线
function drawParticles() {
  const { width, height } = bgCanvas.value
  ctx.value.clearRect(0, 0, width, height)
  
  // 绘制粒子
  ctx.value.fillStyle = 'rgba(0, 255, 255, 0.5)'
  particles.forEach(p => {
    ctx.value.beginPath()
    ctx.value.arc(p.x, p.y, p.size, 0, Math.PI * 2)
    ctx.value.fill()
  })

  // 绘制连线
  ctx.value.strokeStyle = 'rgba(0, 255, 255, 0.2)'
  ctx.value.lineWidth = 0.5
  
  for (let i = 0; i < particles.length; i++) {
    for (let j = i + 1; j < particles.length; j++) {
      const dx = particles[i].x - particles[j].x
      const dy = particles[i].y - particles[j].y
      const distance = Math.sqrt(dx * dx + dy * dy)
      
      if (distance < CONNECT_DISTANCE) {
        ctx.value.beginPath()
        ctx.value.moveTo(particles[i].x, particles[i].y)
        ctx.value.lineTo(particles[j].x, particles[j].y)
        ctx.value.stroke()
      }
    }
  }
}

// 动画循环
function animate() {
  updateParticles()
  drawParticles()
  animationFrame = requestAnimationFrame(animate)
}

// 调整 Canvas 大小
function resizeCanvas() {
  const { width, height } = container.value.getBoundingClientRect()
  bgCanvas.value.width = width
  bgCanvas.value.height = height
  initParticles()
}

// 生命周期钩子
onMounted(() => {
  ctx.value = bgCanvas.value.getContext('2d')
  resizeCanvas()
  animate()
  window.addEventListener('resize', resizeCanvas)
  
  // 淡入内容
  setTimeout(() => {
    contentOpacity.value = 1
  }, 100)
})

onUnmounted(() => {
  if (animationFrame) {
    cancelAnimationFrame(animationFrame)
  }
  window.removeEventListener('resize', resizeCanvas)
})

const exporting = ref(false)
const menuContent = ref(null)

// 导出图片功能
async function exportImage() {
  try {
    exporting.value = true
    
    // 暂时隐藏导出按钮
    const exportButton = document.querySelector('.export-button')
    const originalDisplay = exportButton.style.display
    exportButton.style.display = 'none'
    
    // 保存原始样式和滚动位置
    const originalContentStyle = menuContent.value.style.cssText
    const originalContainerStyle = container.value.style.cssText
    const originalScroll = menuContent.value.scrollTop
    
    // 临时调整样式以捕获完整内容
    container.value.style.height = 'auto'
    container.value.style.overflow = 'visible'
    menuContent.value.style.height = 'auto'
    menuContent.value.style.overflow = 'visible'
    menuContent.value.style.position = 'relative'
    menuContent.value.style.transform = 'none'
    
    // 等待样式更新
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 创建截图
    const canvas = await html2canvas(container.value, {
      backgroundColor: '#000000',
      scale: 2, // 提高导出图片质量
      useCORS: true,
      logging: false,
      allowTaint: true,
      foreignObjectRendering: true,
      width: container.value.scrollWidth,
      height: container.value.scrollHeight,
      windowWidth: container.value.scrollWidth,
      windowHeight: container.value.scrollHeight,
      onclone: (clonedDoc) => {
        const clonedElement = clonedDoc.querySelector('.menu-content')
        if (clonedElement) {
          clonedElement.style.opacity = '1'
          clonedElement.style.transform = 'none'
        }
      }
    })
    
    // 恢复原始样式
    container.value.style.cssText = originalContainerStyle
    menuContent.value.style.cssText = originalContentStyle
    menuContent.value.scrollTop = originalScroll
    
    // 恢复导出按钮
    exportButton.style.display = originalDisplay
    
    // 转换为图片并下载
    const image = canvas.toDataURL('image/png', 1.0)
    const link = document.createElement('a')
    link.download = 'cyber-beer-menu.png'
    link.href = image
    link.click()
  } catch (error) {
    console.error('导出图片失败:', error)
  } finally {
    exporting.value = false
  }
}

async function exportAsImage() {
  try {
    const canvas = await createMenuImage()
    const link = document.createElement('a')
    link.download = 'cyber-beer-menu.png'
    link.href = canvas.toDataURL('image/png')
    link.click()
  } catch (error) {
    console.error('导出图片失败:', error)
  }
}

async function createMenuImage() {
  const element = container.value
  const canvas = await html2canvas(element, {
    backgroundColor: '#000',
    scale: 2,
    logging: false,
    useCORS: true
  })
  return canvas
}

async function exportForCanvas() {
  try {
    const zip = new JSZip()
    
    // 生成菜单图片
    const canvas = await createMenuImage()
    const imageBlob = await new Promise(resolve => {
      canvas.toBlob(resolve, 'image/png')
    })
    zip.file('menu.png', imageBlob)

    // 生成 HTML 文件
    const html = generateCanvasHTML()
    zip.file('index.html', html)

    // 生成 manifest 文件
    const manifest = generateCanvasManifest()
    zip.file('imsmanifest.xml', manifest)

    // 生成并下载 zip 文件
    const content = await zip.generateAsync({ type: 'blob' })
    const link = document.createElement('a')
    link.download = 'cyber-beer-menu-canvas.zip'
    link.href = URL.createObjectURL(content)
    link.click()
  } catch (error) {
    console.error('导出 Canvas 包失败:', error)
  }
}

function generateCanvasHTML() {
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>赛博朋克啤酒菜单</title>
  <style>
    body {
      margin: 0;
      padding: 20px;
      background: #000;
      display: flex;
      justify-content: center;
    }
    img {
      max-width: 100%;
      height: auto;
    }
  </style>
</head>
<body>
  <img src="menu.png" alt="赛博朋克啤酒菜单">
</body>
</html>`
}

function generateCanvasManifest() {
  return `
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns="http://www.imsglobal.org/xsd/imsccv1p1/imscp_v1p1">
  <metadata>
    <schema>IMS Common Cartridge</schema>
    <schemaversion>1.1.0</schemaversion>
  </metadata>
  <organizations>
    <organization identifier="org_1" structure="rooted-hierarchy">
      <item identifier="item_1">
        <title>赛博朋克啤酒菜单</title>
        <item identifier="item_1_1" identifierref="resource_1">
          <title>菜单展示</title>
        </item>
      </item>
    </organization>
  </organizations>
  <resources>
    <resource identifier="resource_1" type="webcontent" href="index.html">
      <file href="index.html"/>
      <file href="menu.png"/>
    </resource>
  </resources>
</manifest>`
}

function goToDisplay() {
  router.push('/tools/beer-menu-display')
}
</script>

<style scoped>
/* 确保字体加载 */
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');

.cyber-menu-container {
  position: relative;
  width: 100%;
  min-height: 100%;
  background: #000;
  overflow: hidden;
  font-family: 'Orbitron', sans-serif;
  color: #0ff;
  display: flex;
  flex-direction: column;
}

.background-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.menu-content {
  position: relative;
  z-index: 2;
  padding: 1rem;
  transition: opacity 1s ease;
  flex: 1;
  overflow-y: auto;
  background: linear-gradient(135deg, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.7) 100%);
  scroll-behavior: smooth;
}

.menu-header {
  text-align: center;
  margin-bottom: 1.5rem;
  text-shadow: 0 0 10px #0ff;
  padding: 0 1rem;
}

.cyber-title {
  font-size: 4rem;
  font-weight: 700;
  letter-spacing: 0.5rem;
  margin: 0;
  animation: glitch 2s infinite;
}

.cyber-subtitle {
  font-size: 1.2rem;
  letter-spacing: 0.2rem;
  color: #0ff;
  margin-top: 0.5rem;
}

.beer-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1rem;
  padding: 0.5rem;
  max-width: 100%;
  margin: 0 auto;
}

.beer-card {
  background: rgba(0,0,0,0.7);
  border: 1px solid #0ff;
  padding: 1rem;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.beer-card:hover, .beer-card.active {
  transform: translateY(-5px);
  box-shadow: 0 0 20px rgba(0,255,255,0.3);
  background: rgba(0,255,255,0.1);
}

.beer-number {
  position: absolute;
  top: 1rem;
  right: 1rem;
  font-size: 1.2rem;
  color: #0ff;
  font-family: 'Courier New', monospace;
}

.beer-name {
  font-size: 1.2rem;
  margin: 0 0 0.5rem;
  color: #fff;
  text-shadow: 0 0 5px #0ff;
}

.beer-style {
  font-size: 0.9rem;
  color: #0ff;
  margin-bottom: 0.5rem;
}

.beer-stats {
  display: flex;
  gap: 0.8rem;
  margin-bottom: 0.5rem;
  font-family: 'Courier New', monospace;
  color: #0ff;
  font-size: 0.9rem;
}

.beer-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.beer-description {
  flex: 1;
  font-size: 0.8rem;
  color: #fff;
  opacity: 0.8;
  margin-bottom: 0.8rem;
  line-height: 1.2;
}

.beer-prices {
  display: flex;
  gap: 1rem;
  margin-top: 0.8rem;
  align-items: center;
  justify-content: flex-end;
}

.price-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.beer-icon {
  color: #0ff;
}

.beer-icon.small {
  transform: scale(0.8);
  opacity: 0.8;
}

.beer-icon.large {
  transform: scale(1.2);
}

.price {
  font-size: 1rem;
  color: #0ff;
  font-weight: bold;
  text-shadow: 0 0 5px #0ff;
  font-family: 'Courier New', monospace;
}

@keyframes glitch {
  0% {
    text-shadow: 0.05em 0 0 #00fffc, -0.03em -0.04em 0 #fc00ff,
                 0.025em 0.04em 0 #fffc00;
  }
  15% {
    text-shadow: 0.05em 0 0 #00fffc, -0.03em -0.04em 0 #fc00ff,
                 0.025em 0.04em 0 #fffc00;
  }
  16% {
    text-shadow: -0.05em -0.025em 0 #00fffc, 0.025em 0.035em 0 #fc00ff,
                 -0.05em -0.05em 0 #fffc00;
  }
  49% {
    text-shadow: -0.05em -0.025em 0 #00fffc, 0.025em 0.035em 0 #fc00ff,
                 -0.05em -0.05em 0 #fffc00;
  }
  50% {
    text-shadow: 0.05em 0.035em 0 #00fffc, 0.03em 0 0 #fc00ff,
                 0 -0.04em 0 #fffc00;
  }
  99% {
    text-shadow: 0.05em 0.035em 0 #00fffc, 0.03em 0 0 #fc00ff,
                 0 -0.04em 0 #fffc00;
  }
  100% {
    text-shadow: -0.05em 0 0 #00fffc, -0.025em -0.04em 0 #fc00ff,
                 -0.04em -0.025em 0 #fffc00;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(0,0,0,0.3);
}

::-webkit-scrollbar-thumb {
  background: #0ff;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #0aa;
}

.export-button {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  background: rgba(0, 255, 255, 0.2);
  border: 1px solid #0ff;
  color: #0ff;
  padding: 0.8rem 1.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  font-family: 'Orbitron', sans-serif;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
  z-index: 100;
}

.export-button:hover {
  background: rgba(0, 255, 255, 0.3);
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
}

.export-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.export-button svg {
  width: 1.5rem;
  height: 1.5rem;
}

.loading-spinner {
  width: 1.5rem;
  height: 1.5rem;
  border: 2px solid rgba(0, 255, 255, 0.3);
  border-top: 2px solid #0ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.export-buttons {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 10px;
  z-index: 1000;
}

.cyber-button {
  background: rgba(0, 0, 0, 0.7);
  border: 1px solid #0ff;
  color: #0ff;
  padding: 10px 20px;
  font-family: 'Orbitron', sans-serif;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cyber-button:hover {
  background: rgba(0, 255, 255, 0.1);
  box-shadow: 0 0 10px #0ff;
}

.cyber-button i {
  font-size: 1.2em;
}

.beer-menu {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Roboto', sans-serif;
}

.config-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 添加响应式布局 */
@media (max-width: 1600px) {
  .beer-grid {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1200px) {
  .beer-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

@media (max-width: 900px) {
  .beer-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 600px) {
  .beer-grid {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }
  
  .menu-header {
    margin-bottom: 1rem;
  }
  
  .cyber-title {
    font-size: 2.5rem;
  }
}
</style> 